package com.health.mapp.service;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.health.mapp.service.Download;
import com.health.commons.CommonsUtils;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.MappGlobal;

public class Download extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 109920102112L;

	private static final String DEFAULT_ENCODING = "UTF-8";

	private static final int DEFAULT_BUFFER_SIZE = 4096;

	private static Logger logger = Logger.getLogger(Download.class);
	private static Logger eventLogger = Logger.getLogger(Constant.EVENT_LOG_TAG);

	/**
	 * Constructor of the object.
	 */
	public Download() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 * 
	 *             download url : http://xxxx/Download?appid=sjb&uid=10002 gen
	 *             url : http://xxxx/Download?channel=CHN0000&gen=18618600000
	 * 
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String appid = request.getParameter("appid");
		String uid = request.getParameter("uid");
		String gen = request.getParameter("gen");

		// 生成下载链接
		if (null != gen && !gen.isEmpty()) {
			int userid = 0;
//			TMarketingDao dao = new TMarketingDao();
//			TMarketing marketing = dao.selectByMdn(gen);
//
//			if (null == marketing) {
//				TMarketing record = new TMarketing();
//				record.setMdn(gen);
//				record.setChannel(request.getParameter("channel"));
//				record.setTs(CommonsUtils.getDateTimeByFmt("yyyy-MM-dd HH:mm:ss"));
//				dao.insert(record);
//				marketing = dao.selectByMdn(gen);
//			}
//			if (null != marketing) {
//				userid = marketing.getUid();
//			}

			String resultUrl = String.format(MappGlobal.getInstance()
					.getPropertiesConfig().get("marketing.url.generator"),
					userid);

			logger.debug(String.format("user(%s) download url is : %s", gen, resultUrl));
			
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.println(resultUrl);
			out.flush();
			out.close();
		} else if (null != uid && null != appid && !uid.isEmpty() && !appid.isEmpty()) {
 			if (appid.equalsIgnoreCase("SJB")) { } else {
				logger.warn("appid unsopport("+appid+")");
				response.sendError(HttpServletResponse.SC_NOT_FOUND);
			}
		} else {
			logger.warn(String.format("Parameter parse error.appid=%s, uid=%s, gen=%s", appid, uid, gen));
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
		}

	}

	private boolean generateAPK(String strChannel, String version, String strMdn) {
		Runtime run = Runtime.getRuntime();// 返回与当�?Java 应用程序相关的运行时对象
		boolean runResult = true;
		try {
			//
			String command = String.format(MappGlobal.getInstance()
					.getPropertiesConfig().get("marketing.cmd.generator.apk"),
					strChannel, version, strMdn);

			logger.debug("generate command :" + command);

			Process p = run.exec(command);// 启动另一个进程来执行命令
			 BufferedInputStream in = new
			 BufferedInputStream(p.getInputStream());
			 BufferedReader inBr = new BufferedReader(new
			 InputStreamReader(in));
			 String lineStr;
			 while ((lineStr = inBr.readLine()) != null) {
				 // 获得命令执行后在控制台的输出信息
				 logger.debug(lineStr);// 打印输出信息
			 }
			// �?��命令是否执行失败�?
			if (p.waitFor() != 0) {
				if (p.exitValue() == 1) { // p.exitValue()==0表示正常结束�?：非正常结束
					runResult = false;
					logger.error("命令执行失败!");
				}
			}
			 inBr.close();
			 in.close();
		} catch (Exception e) {
			runResult = false;
			logger.error("命令执行失败!");
			e.printStackTrace();
		}
		return runResult;
	}
	
	private void eventLog(String appid, int infoType, String channel, String version, String recommended) {
		StringBuffer sb = new StringBuffer();
		// 应用ID
		sb.append(appid);
		sb.append("\t");
		// 记录IMSI信息
		sb.append("");
		sb.append("\t");
		// MDN信息
		sb.append("");
		sb.append("\t");
		// 运营商信�?
		sb.append("");
		sb.append("\t");
		// 省份信息
		sb.append("");
		sb.append("\t");
		// SIM品牌
		sb.append("");
		sb.append("\t");
		// 套餐信息
		sb.append("");
		sb.append("\t");

		// 事务日志内容
		StringBuffer sbEventLog = new StringBuffer();
		sbEventLog.append("{");
		sbEventLog.append("\"channel\":\"").append(channel).append("\",");
		sbEventLog.append("\"version\":\"").append(version).append("\",");
		sbEventLog.append("\"infoType\":").append(infoType).append(",");
		sbEventLog.append("\"recommended\":\"").append( recommended ).append("\"");
		sbEventLog.append("}");
		
		sb.append(sbEventLog.toString());
		eventLogger.info(sb.toString());
	}
	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
